package com.example.joblinker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.joblinker.dto.LoginDTO;
import com.example.joblinker.dto.RegisterDTO;
import com.example.joblinker.entity.User;
import com.example.joblinker.mapper.UserMapper;
import com.example.joblinker.service.UserService;
import com.example.joblinker.util.JwtUtil;
import com.example.joblinker.util.MD5Util;
import com.example.joblinker.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserMapper userMapper;

    @Override
    public UserVO register(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, registerDTO.getUsername());
        if (this.count(queryWrapper) > 0) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱是否已存在
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, registerDTO.getEmail());
        if (this.count(queryWrapper) > 0) {
            throw new RuntimeException("邮箱已被注册");
        }

        // 创建用户
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        // MD5加密密码
        user.setPassword(MD5Util.encrypt(registerDTO.getPassword()));
        // 保存用户
        this.save(user);

        // 生成包含角色的token
        String token = JwtUtil.generateToken(user.getId(), user.getRole());

        // 转换为视图对象
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setToken(token);

        return userVO;
    }

    @Override
    public UserVO login(LoginDTO loginDTO) {
        // 查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, loginDTO.getUsername());
        User user = this.getOne(queryWrapper);

        // 验证用户是否存在
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 验证密码
        if (!user.getPassword().equals(MD5Util.encrypt(loginDTO.getPassword()))) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 生成包含角色的token
        String token = JwtUtil.generateToken(user.getId(), user.getRole());

        // 转换为视图对象
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setToken(token);

        return userVO;
    }

    @Override
    public UserVO getCurrentUser(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            throw new RuntimeException("未登录或token已失效");
        }
        token = token.substring(7);

        // 验证token并获取用户ID
        if (!jwtUtil.validateToken(token)) {
            throw new RuntimeException("token已失效");
        }
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId == null) {
            throw new RuntimeException("token无效");
        }

        // 查询用户信息
        User user = this.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 转换为视图对象
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setToken(token);

        return userVO;
    }

    @Override
    public Page<UserVO> getUserList(Integer page, Integer size, String keyword) {
        // 创建分页对象
        Page<User> userPage = new Page<>(page, size);
        
        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like(User::getUsername, keyword)
                    .or()
                    .like(User::getEmail, keyword)
                    .or()
                    .like(User::getPhone, keyword);
        }
        
        // 执行查询
        Page<User> result = this.page(userPage, queryWrapper);
        
        // 转换为VO对象
        Page<UserVO> voPage = new Page<>();
        BeanUtils.copyProperties(result, voPage, "records");
        
        List<UserVO> voList = result.getRecords().stream().map(user -> {
            UserVO vo = new UserVO();
            BeanUtils.copyProperties(user, vo);
            return vo;
        }).collect(Collectors.toList());
        
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public void updateUserStatus(Long id, Integer status) {
        // 检查用户是否存在
        User user = this.getById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查状态值是否有效
        if (status != 0 && status != 1) {
            throw new RuntimeException("无效的状态值");
        }
        
        // 更新状态
        user.setStatus(status);
        if (!this.updateById(user)) {
            throw new RuntimeException("更新用户状态失败");
        }
    }

    @Override
    public void resetUserPassword(Long id) {
        // 检查用户是否存在
        User user = this.getById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 重置密码为123456
        user.setPassword(MD5Util.encrypt("123456"));
        if (!this.updateById(user)) {
            throw new RuntimeException("重置密码失败");
        }
    }

    @Override
    public boolean updateUser(UserVO userVO) {
        if (userVO == null || userVO.getId() == null) {
            throw new RuntimeException("用户信息不能为空");
        }
        
        User user = userMapper.selectById(userVO.getId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 更新用户信息
        user.setUsername(userVO.getUsername());
        user.setEmail(userVO.getEmail());
        user.setPhone(userVO.getPhone());
        user.setStatus(userVO.getStatus());
        
        return userMapper.updateById(user) > 0;
    }

    @Override
    public boolean deleteUser(Long id) {
        if (id == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        return userMapper.deleteById(id) > 0;
    }

    @Override
    public String getUsernameById(Long userId) {
        User user = userMapper.selectById(userId);
        return user != null ? user.getUsername() : null;
    }
    
    @Override
    public String getUserRole(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 将整数角色转换为字符串角色标识
        switch (user.getRole()) {
            case 0:
                return "ROLE_USER";  // 求职者
            case 1:
                return "ROLE_HR";    // 招聘者
            case 2:
                return "ROLE_ADMIN"; // 管理员
            default:
                return "ROLE_USER";  // 默认为求职者角色
        }
    }
} 